<template>
	<view class="set-target">
		<u-navbar
			bgColor="transparent"
			placeholder
			title="设置目标"
			@leftClick="back"
			leftIcon="close"
			leftIconColor="rgba(255,255,255,0.3)"
			titleStyle="color: #C2D5D9;font-weight: bold;">
			<view slot="right" class="title-right"
			@click="confirm">确认</view>
		</u-navbar>
		<view class="flex-no-horizontal between m-b-20">
			<text class="title-color f-large bold">睡眠目标</text>
			<view class="f-xs sub-color flex-no-horizontal">
				<u-icon name="info-circle" size="14"
				class="m-r-5"
				color="rgba(194, 213, 217, 0.5)"></u-icon>
			 入睡时间将直接影响获得元气效率
			</view>
		</view>
		<view class="wrap">
			<view class="flex-no-horizontal between">
				<view class="target flex-no-horizontal"
				@click="chooseTime('sleep')"
				:class="sleepTime.sleep ? '' : 'not-target'">
					<u--image src="https://cdn3.relaverse.cn/appfile/sleep-moon.png"
					width="18" height="auto" mode="widthFix"></u--image>
					<text class="f-base target-title sleep-down">入睡</text>
					<text class="title-color bold"
					:class="sleepTime.sleep ? 'f-large' : 'f-base'">
						{{sleepTime.sleep ? sleepTime.sleep : '点击设置'}}
					</text>
				</view>
				<view class="target flex-no-horizontal"
				@click="chooseTime('getUp')"
				:class="sleepTime.getUp ? '' : 'not-target'">
					<u--image src="https://cdn3.relaverse.cn/appfile/sleep-sun.png"
					width="18" height="auto" mode="widthFix"></u--image>
					<text class="f-base target-title get-up">起床</text>
					<text class="title-color bold"
					:class="sleepTime.getUp ? 'f-large' : 'f-base'">
						{{sleepTime.getUp ? sleepTime.getUp : '点击设置'}}
					</text>
				</view>
			</view>
			<view class="text-center f-xs m-t-20" v-show="sleepTime.sumMintues">
				<text class="sub-color">预计睡眠时长：</text>
				<text class="bold" style="color: #00B49D;">
					{{sleepTime.showTime}}
				</text>
			</view>
		</view>
		<view class="flex-no-horizontal between m-b-15">
			<text class="f-large bold title-color">起床闹钟</text>
			<u-switch v-model="isAlarm"
			:inactiveValue="0"
			:activeValue="1"
			inactiveColor="rgba(194, 213, 217, 0.5)"
			size="20" activeColor="#008886"></u-switch>
		</view>
		<view class="wrap flex-no-horizontal between" v-show="isAlarm">
			<view class="sub-color f-base">铃声选择</view>
			<view class="flex-no-horizontal" @click="isShowAlerm = true">
				<view class="f-xs sub-color m-r-5"
				v-if="choseAlarm && choseAlarm.chose">
					{{choseAlarm.name}}
				</view>
				<u-icon name="arrow-right" color="rgba(255,255,255,0.3)" size="12"></u-icon>
			</view>
		</view>
		<view class="flex-no-horizontal between m-b-15">
			<text class="f-large bold title-color">睡眠引导</text>
			<u-switch v-model="isGuided"
			:inactiveValue="0"
			:activeValue="1"
			inactiveColor="rgba(194, 213, 217, 0.5)"
			size="20" activeColor="#008886"></u-switch>
		</view>
		<view class="wrap flex-no-horizontal between" v-show="isGuided">
			<view class="sub-color f-base">引导选择</view>
			<view class="flex-no-horizontal" @click="isShowGuide = true">
				<view class="f-xs sub-color m-r-5"
				v-if="choseGuide && choseGuide.chose">
					{{choseGuide.name}}
				</view>
				<u-icon name="arrow-right" color="rgba(255,255,255,0.3)" size="12"></u-icon>
			</view>
		</view>
		<!-- 选择时间 -->
		<!-- <picker mode="time" v-model=""></picker> -->
		<u-datetime-picker
			v-if="isShowChooseTime"
			ref="datetimePicker"
			:show="isShowChooseTime"
			v-model="now"
			mode="time"
			title="选择时间"
			confirmColor="#00B49D"
			cancelColor="rgba(180, 186, 213, 0.3)"
			@confirm="confirmTime"
			@cancel="isShowChooseTime = false"
		></u-datetime-picker>
		<!-- 选择铃声 -->
		<u-popup :show="isShowAlerm" @close="closeAlarm"
		mode="bottom" overlayOpacity="0.8" safeAreaInsetBottom
		round="25" bgColor="#1A2533" closeIconPos="top-left">
			<view class="alarm-muen">
				<view class="alarm-muen-title flex-no-horizontal">
					<u-icon name="close" size="16"
					@click="closeAlarm"
					color="rgba(255,255,255,0.3)"></u-icon>
					<text class="title-color f-large bold">选择铃声</text>
					<text class="f-large bold green" @click="confirmAlarm">确认</text>
				</view>
				<z-paging ref="paging" class="alarm-content"
				:refresher-enabled="false" :fixed="false"
				:safe-area-inset-bottom="true"
				lower-threshold="244rpx"
				:show-loading-more-no-more-view="false"
				v-model="alarmList"@query="queryAlarmList">
					<view class="alarm-item flex-no-horizontal between"
					@click="chooseAlarm(index)"
					v-for="(item,index) in alarmList"
					:key="item.id"
					:class="item.chose ? 'isChose' : ''">
						<view class="flex-no-horizontal">
							<view class="m-r-5">{{item.name}}</view>
							<view class="audioClass" style="">
								<view @tap.stop="onMyaudio(`myCanvas${item.id}`, item, index, 'tones')" style="width: 16px; z-index: 2; position: absolute; height: 16px;"></view>
								<view style="z-index: 1; position: absolute;right: 1px; top: 1px;">
									<my-audio :id="`myCanvas${item.id}`" :music="item.source" ref="myAudios"></my-audio>
								</view>
							</view>
						</view>
						<view class="circle" :class=" item.chose ? 'chosed' : ''">
							<u-icon name="checkbox-mark" color="white" size="11"
							v-show="item.chose"></u-icon>
						</view>
					</view>
				</z-paging>
			</view>
		</u-popup>
		<!-- 选择引导 -->
		<u-popup :show="isShowGuide" @close="isShowGuide = false"
		mode="bottom" overlayOpacity="0.8" safeAreaInsetBottom
		:customStyle="{'height': '50%'}"
		round="25" bgColor="#1A2533" closeIconPos="top-left">
			<view class="alarm-muen">
				<view class="alarm-muen-title flex-no-horizontal">
					<u-icon name="close" size="16"
					@click="closeIsShowGuide()"
					color="rgba(255,255,255,0.3)"></u-icon>
					<u-tabs :list="tabList" lineColor="#B4BAD5"
					@click="checkTab"
					:activeStyle="{
					            color: '#B4BAD5',
					            fontWeight: 'bold',
					            fontSize: '16px'
					        }"
					:inactiveStyle="{
								color: 'rgba(180, 186, 213, 0.3)',
								fontWeight: 'bold',
								fontSize: '16px'
							}"
					></u-tabs>
					<text class="f-large bold green" @click="confirmGuide">确认</text>
				</view>
				<z-paging ref="paging" class="alarm-content"
				:refresher-enabled="false" :fixed="false"
				:safe-area-inset-bottom="true"
				lower-threshold="244rpx"
				:show-loading-more-no-more-view="false"
				v-model="guideList" @query="queryGuideList">
					<view class="alarm-item flex-no-horizontal between"
					@click="chooseGuide(index)"
					v-for="(item,index) in guideList"
					:key="item.id"
					:class="item.chose ? 'isChose' : ''">
						<view class="flex-no-horizontal">
							<view class="m-r-5">{{item.name}}</view>
							<!-- <my-audio :id="'myCanvas' + item.id"
							ref="myAudio"
							:music="item.source"></my-audio> -->
							<view class="audioClass" style="">
								<view @tap.stop="onMyaudio(`myCanvas${item.id}`, item, index, 'guide')" style="width: 16px; z-index: 2; position: absolute; height: 16px;"></view>
								<view style="z-index: 1; position: absolute;right: 1px; top: 1px;">
									<my-audio @getTime="getTime($event, index)" :id="`myCanvas${item.id}`" :music="item.source" ref="myAudios"></my-audio>
								</view>
							</view>
							<view class="duration">
								{{item.time}}
							</view>
						</view>
						<view class="circle" :class=" item.chose ? 'chosed' : ''">
							<u-icon name="checkbox-mark" color="white" size="11"
							v-show="item.chose"></u-icon>
						</view>
					</view>
				</z-paging>
			</view>
		</u-popup>
		<!-- 提醒 -->
		<u-popup :show="isShowTip" @close="isShowTip = false"
		overlayOpacity="0.8" safeAreaInsetBottom mode="center"
		round="25" bgColor="#1A2533" closeIconPos="top-left">
			<view class="sleep-tip">
				<u--image src="https://cdn3.relaverse.cn/appfile/sleep-not-enough-icon.png"
				width="70" height="70" shape="circle" class="sleep-tip-icon"></u--image>

				<view class="text-center sleep-tip-text"
				v-if="isShowTipFour">
					睡眠时间必须在
					<text style="color: #00ACB3;">{{$store.state.sleepConfig.min_duration}}</text>
					小时-
					<text style="color: #00ACB3;">{{$store.state.sleepConfig.max_duration}}</text>
					小时之间
				</view>
				<view class="text-center sleep-tip-text"
				v-else-if="isShowTipOne">
					入睡时间在 <text style="color: #00ACB3;">{{standardSleepTime/60}}</text> 点之后<br>本次睡眠不会产生能量
				</view>
				<view class="text-center sleep-tip-text"
				v-else-if="isShowTipTwo">
					睡眠时间小于 <text style="color: #00ACB3;">{{$store.state.sleepConfig.shortest}}</text> 小时<br> 本次睡眠不会产生能量
				</view>
				<view class="text-center sleep-tip-text"
				v-else-if="isShowTipThree">
					睡眠时间必须小于 <text style="color: #00ACB3;">24</text> 小时
				</view>
				<view class="sleep-tip-button text-center" @click="isShowTip = false">我知道了</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	let audioContext = uni.createInnerAudioContext()
	audioContext.autoplay = true;
	import MyAudio from './components/audio.vue'
	import {musiclist,musicCate,setTarget,
	getTargetApi} from '../../api/sleep.js'
	import {getMintues} from './components/sleep.js'
	export default{
		components: {MyAudio},
		data() {
			return{
				isShowChooseTime: false,
				sleepTime: null,
				choseTime: 0,
				now: '8:00',
				chooseTimeType: 'sleep',
				sleepSum: 0,
				isAlarm: 1,
				isShowAlerm: false,
				isGuided: 1,
				isShowGuide: false,
				tabList: [],
				active: 0,
				alarmId: 0,
				guideList: [],
				choseGuide: {},
				alarmList: [],
				choseAlarm: null,
				isShowTip: false,
				page: 1,
				isShowTipThree: false,
				isPlay: false,//是否播放
				previousMusicIndex: '',//上一个音乐下标
				lastOneType: {
					types: 1,//第一次进行赋值index
					typeGuide: 1,//引导第一次进行赋值
					guideIndex:0
				}

			}
		},
		//释放音频
		onUnload() {
			audioContext.offTimeUpdate()
			audioContext.offEnded()
			audioContext.offError()
			audioContext.destroy()
		},
		async onLoad() {
			this.sleepTime = this.$store.state.sleepData ? this.$store.state.sleepData : {
					sleep: null,
					getUp: null,
					sumMintues: 0,
					showTime: 0
				},
			await this.getTarget()
			this.getAlarm()
			this.getGuide()
		},
		computed: {
			standardSleepTime() {
				return this.$store.state.sleepConfig.fall_asleep == 0 ?  24 * 60 : this.$store.state.sleepConfig.fall_asleep * 60
			},
			isShowTipOne() {
				return this.sleepTime.sleep && Number(this.sleepTime.sleep.split(":")[0] * 60) + Number(this.sleepTime.sleep.split(":")[1]) > this.standardSleepTime
			},
			isShowTipTwo() {
				if (!this.sleepTime.sleep || !this.sleepTime.getUp) return false
				return this.sleepTime.sumMintues < this.$store.state.sleepConfig.shortest * 60
			},
			isShowTipFour() {
				return this.sleepTime.sumMintues > this.$store.state.sleepConfig.max_duration * 60 || this.sleepTime.sumMintues < this.$store.state.sleepConfig.min_duration * 60
			}
		},
		methods: {
			/**
			 * 点击开始播放起床铃声或引导
			 * @param {Number} id  音乐ID
			 * @param {Object} item 音乐属性值
			 * @param {Number} index 选择下标
			 */
			onMyaudio(id, item, index){
				this.$nextTick(()=>{
					this.isPlay = !this.isPlay
					if(this.lastOneType.types == 1){
						this.previousMusicIndex = index
						this.$refs.myAudios[this.previousMusicIndex].onPlays(id, item.source, true)
						this.onAudioPlay(item)
						this.lastOneType.types = 2
					} else {
						if(this.previousMusicIndex != index){
							this.onIsPlay(id, item,index)
							this.previousMusicIndex = index
						} else {
							this.onIsPlay(id, item,index)
							audioContext.onPlay(() => {
								 this.isPlay = true
							});
							audioContext.onEnded(() => {
								 this.isPlay = false
							});
							this.musicId = this.musicId
							this.$refs.myAudios[index].onPlays(id, item.source, this.isPlay)
						}
					}
				})
			},
			//判断音频是否正在播放
			onIsPlay(id, item, index){
				this.$refs.myAudios[this.previousMusicIndex].onPlays(id, item.source, false)
				this.$refs.myAudios[index].onPlays(id, item.source, true)
				if (this.isPlay) {
					audioContext.src = item.source
					audioContext.play()
				} else {
					audioContext.pause()
					audioContext.onPause(() => {//暂停监听
						 this.isPlay = false
					});
					if(this.previousMusicIndex != index){
						audioContext.src = item.source
						audioContext.play()
					}
				}
			},
			//音频播放
			onAudioPlay(item){
				audioContext.src = item.source
				audioContext.play()
			},
			//释放音频
			destroyed() {
				if (audioContext) {
					audioContext.offTimeUpdate()
					audioContext.offEnded()
					audioContext.offError()
					audioContext.destroy()
					audioContext = null
				}
			},
			//获取睡眠目标
			async getTarget() {
				try{
					const res = await getTargetApi()
					this.choseGuide = {
						chose: true,
						...res.data.checked_guide
					}
					this.isAlarm = res.data.music_state
					this.choseAlarm = {
						chose: true,
						...res.data.checked_music
					}
					this.isGuided = res.data.guide_state
					this.hasHardware = res.data.is_has_hardware
				}catch(e){
					console.log(e)
					//TODO handle the exception
				}
			},
			//音乐分类
			async getGuide() {
				try{
					const res = await musicCate({music_type: 'guide'})
					if (res.data.is_show) {
						res.data.cate.forEach(item => {
							this.tabList.push({name: item.name,id: item.id})
						})
					}
				}catch(e){
					console.log(e)
					//TODO handle the exception
				}
			},
			getTime(time,index) {
				this.$set(this.guideList[index], 'time', time)
			},
			//引导铃声列表
			async queryGuideList(pageNo, pageSize) {
				try{
					const res = await this.getMusicList('guide',pageNo,this.tabList[this.active].id)
					res.data.data.forEach(item => {
						item.music_id == this.choseGuide.id ? item.chose = true : item.chose = false
					})
					this.$refs.paging.complete(res.data.data);

				}catch(e){
					this.$refs.paging.complete(false);
					//TODO handle the exception
				}
			},

			//音乐分类
			async getAlarm() {
				try{
					const res = await musicCate({music_type: 'music'})
					this.alarmId = res.data.cate[0].id
				}catch(e){
					console.log(e)
					//TODO handle the exception
				}
			},
			//获取铃声列表
			async queryAlarmList(pageNo, pageSize) {
				try{
					const res = await this.getMusicList('music',pageNo,this.alarmId)
					let list = []
					res.data.data.forEach(item => {
						list.push({
							...item,
							chose: item.music_id == this.choseAlarm.id ? true : false,
							isShowType: false
						})
					})
					this.$refs.paging.complete(list);
				}catch(e){
					console.log(e)
					this.$refs.paging.complete(false);
					//TODO handle the exception
				}
			},
			//获取音乐列表
			getMusicList(type,page,cateId) {
				return new Promise(async (resolve,reject) => {
					try{
						const res = await musiclist({
							music_type: type,
							page: page,
							cate_id: cateId
						})
						resolve(res)
					}catch(e){
						console.log(e)
						reject(e)
						//TODO handle the exception
					}
				})
			},
			back() {
				this.destroyed()
				uni.navigateBack()
			},
			//设置睡眠目标
			async confirm() {
				if (this.isShowTipFour) {
					this.isShowTip = true
					return
				}
				try{
					const res = await setTarget({
						start_time: this.sleepTime.sleep,
						end_time: this.sleepTime.getUp,
						music_id: this.choseAlarm.id,
						music_state: this.isAlarm,
						guide_state: this.isGuided,
						guide_id: this.choseGuide.id
					})
					const object = Object.assign(this.sleepTime, {
						checked_music: this.choseAlarm,
						checked_guide: this.choseGuide,
						music_state: this.isAlarm,
						guide_state: this.isGuided,
					})
					this.$store.commit('setSleepTartget',object)
					uni.removeStorageSync('aheadFinish')
					uni.$emit('changeTarget')
					this.back()
				}catch(e){
					console.log(e)
					//TODO handle the exception
				}

			},
			chooseTime(type) {
				if (this.sleepTime[type]) {
					this.now = this.sleepTime[type]
				}
				this.isShowChooseTime = true
				this.chooseTimeType = type
			},
			closeChooseTime() {
				this.isShowChooseTime = false
			},
			confirmTime(e) {
				this.sleepTime[this.chooseTimeType] = e.value
				if (this.sleepTime.sleep && this.sleepTime.getUp) {
					const {sumMintues, showTime} = getMintues(this.sleepTime.sleep,this.sleepTime.getUp)
					this.sleepTime.sumMintues = sumMintues
					this.sleepTime.showTime = showTime
				}
				this.closeChooseTime()
				if (this.chooseTimeType == 'sleep' && this.isShowTipOne && this.hasHardware) {
					this.isShowTip = true
					return
				}

				if (this.chooseTimeType == 'getUp' && this.isShowTipTwo && this.hasHardware) {
					this.isShowTip = true
					return
				}

				if (this.isShowTipFour) {
					this.isShowTip = true
				}
			},
			//关闭铃声弹框
			closeAlarm() {
				this.isShowAlerm = false
				audioContext.pause()
			},
			//铃声弹框确认选择
			confirmAlarm() {
				this.closeAlarm()
				this.closeMusic('alarmList','choseAlarm')
			},
			chooseAlarm(index) {
				this.chooseMusic('alarmList','choseAlarm',index)
			},
			checkTab(item) {
				this.active = item.index
				this.$refs.paging.reload()
			},
			//关闭引导弹框
			closeIsShowGuide() {
				this.isShowGuide = false
				audioContext.pause()
			},
			//引导弹框确认选择
			confirmGuide() {
				this.closeIsShowGuide()
				this.closeMusic('guideList','choseGuide')
			},
			chooseGuide(index) {
				this.chooseMusic('guideList','choseGuide',index)
			},
			chooseMusic(array,target,index) {
				this.$data[array][index].chose = !this.$data[array][index].chose
				this.$data[array].forEach(item => {
					item.id != this.$data[array][index].id ? item.chose = false : ''
				})
				this.$data[target] = this.$data[array][index]
			},
			closeMusic(array,target) {
				let index = 0
				let chosedMusicIndex = 0
				this.$data[array].filter((item,i) => {
					if (item.id == this.$data[target].id) {
						index = i
					}
					if (item.chose) {
						chosedMusicIndex = i
					}
				})
				this.$data[target] = this.$data[array][chosedMusicIndex]
			},
		},
	}
</script>

<style scoped lang="scss">
	.audioClass{
		position: relative;
		border-radius: 50%;
		width: 18px;
		height: 18px;
		border: 1px solid #C2D5D9;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.set-target{
		background-color: #1A2533;
		height: 100vh;
		padding: 60rpx 30rpx;
		.title-color{
			color: #C2D5D9;
		}
		.sub-color{
			color: rgba(194, 213, 217, 0.5);
		}
		.green{
				color: #00B49D;
		}
		.title-right{
			font-weight: bold;
			color: #00B49D;
			font-size: 16px;
		}
		.wrap{
			border-radius: 20rpx;
			background-color: rgba(217, 247, 255, 0.1);
			padding: 40rpx;
			margin-bottom: 50rpx;
			.target{
				width: calc(50% - 20rpx);
				padding: 35rpx 20rpx;
				background-color: rgba(26, 37, 51, 0.5);
				border-radius: 20rpx;
				box-sizing: border-box;
				.target-title{
					padding-left: 10rpx;
					padding-right: 20rpx;
				}
				.sleep-down{
					color: #3BD6CC;
				}
				.get-up{
					color: #F3E19D;
				}
			}
			.not-target{
				opacity: 0.5;
			}
		}
	}
	.set-target ::v-deep {
		.u-popup__content{
			background-color: #1E2B3B;
		}
		.uni-picker-view-mask{
			top: 0;
			height: 100%;
			margin: 0 auto;
			// background: -webkit-linear-gradient(top, rgba(30, 43, 59, 0.95), rgba(30, 43, 59, 0.6)), -webkit-linear-gradient(bottom, rgba(30, 43, 59, 0.95), rgba(30, 43, 59, 0.6));
			background: linear-gradient(180deg, rgba(30, 43, 59, 0.95), rgba(30, 43, 59, 0.6)), linear-gradient(0deg, rgba(30, 43, 59, 0.95), rgba(30, 43, 59, 0.6));
			background-position: top,bottom;
			background-size: 100% 102px;
			background-repeat: no-repeat;
		}
		.u-picker__view__column__item{
			color: #B4BAD5;
			// font-size: 28px;
		}
		.uni-picker-view-indicator:after{
			border-bottom: 1px solid rgba(255, 255, 255, 0.2);
		}
		.uni-picker-view-indicator:before{
			border-top: 1px solid rgba(255, 255, 255, 0.2);
		}
		.u-toolbar__title[data-v-55c89db1] {
		    font-weight: bold;
		    color: #B4BAD5;
		}
		.u-toolbar__wrapper__confirm{
			font-weight: bold;
			font-size: 16px;
		}
	}
	.alarm-muen{
		height: 65vh;
		.alarm-muen-title{
			padding: 50rpx 30rpx;
			justify-content: space-between;
		}
		.alarm-content{
			height: calc(100% - 142rpx);
			overflow-y: scroll;
		}
		.alarm-item{
			padding: 40rpx 30rpx;
			font-weight: 500;
			color: #B4BAD5;
			font-size: 14px;
			background-color: #1E2B3B;
			border-bottom: 1px solid rgba(180, 186, 213, 0.1);
			.circle{
				width: 36rpx;
				height: 36rpx;
				border: 1px solid #B4BAD5;
				opacity: 0.7;
				border-radius: 50%;
			}
			.chosed{
				display: flex;
				justify-content: center;
				align-items: center;
				border: 1px solid #00B49D;
				background-color: #00B49D;
				opacity: 1;
			}
			.duration{
				color: rgba(180, 186, 213, 0.2);
				margin-left: 20rpx;
			}
		}
		.isChose{
			background-color: rgba(222, 226, 255, 0.05);
		}
	}
	.sleep-tip{
		background: url(https://cdn3.relaverse.cn/appfile/sleep-not-enough.png) no-repeat;
		background-size: 100% 100%;
		border-radius: 30rpx;
		padding: 55rpx;
		padding-top: 90rpx;
		position: relative;
		width: 590rpx;
		box-sizing: border-box;
		.sleep-tip-icon{
			position: absolute;
			top: -35px;
			left: calc(50% - 35px);
		}
		.sleep-tip-text{
			font-size: 14px;
			font-weight: 400;
			color: #B4BAD5;
			line-height: 53rpx;
		}
		.sleep-tip-button{
			margin-top: 58rpx;
			height: 96rpx;
			line-height: 96rpx;
			background: rgba(206, 221, 255, 0.2);
			border-radius: 48px;
			font-weight: bold;
			color: #B4BAD5;
			font-size: 14px;
		}
	}
</style>
